from socket import *
from gi.repository import Gtk, GObject, Gst
import threading, time
from notify import notify
from noc_client import AlertWindowDialog
import noc_client
from netCheck import netCheck
from configobj import ConfigObj

import pygst ,json
import pygtk
import sys,os



class registerOkitooPort(object):
	
	def __init__(self):
		self.sock = socket(AF_INET, SOCK_DGRAM)
		self.alertWindow = AlertWindowDialog.AlertWindowDialog()
		thread = threading.Thread(target=self.reg,args=())
        	thread.start()
		
	def reg(self):
		
		#print 'waleed|'+Gtk.session_id+'|rami'
		registrar = {}
		registrar["session_id"] = Gtk.session_id
		registrar["client_type"] = 'ubuntu_noc_client'
		registrar["client_id"] = Gtk.client_id
		registrarEncoded = json.dumps(registrar)
		#print registrarEncoded
		#print Gtk.server
		try:
			self.sock.sendto(registrarEncoded, (Gtk.server, 1030))
			self.sock.settimeout(5)    	
			data, server = self.sock.recvfrom(255)
		except:
			time.sleep(5)
			#print "oops"
			GObject.idle_add(self.reg)
			
		#print data
		if data == "OK":
			GObject.idle_add(self._errorTrigger)
			GObject.timeout_add(20000, self.keepAlive)

			
	def keepAlive(self):
		#print "Are You Gone ?"		
		#print 'waleed|'+Gtk.session_id+'|rami'

		try :
			self.sock.sendto('Are You Gone ?', (Gtk.server, 1030))
			#self.sock.settimeout(5)
	         	#data, server = self.sock.recvfrom(255)
		except:
			#print "Timeout or no network"
			config = ConfigObj('config.dat')
			email = config['email']
			passw = config['passw']
			netCheck(noc_client.do_login,email,passw)

		GObject.timeout_add(30000, self.keepAlive)

	def _errorTrigger(self):
		WaiterThread = threading.Thread(target=self.waitForError,args=())
        	WaiterThread.daemon = True
        	WaiterThread.start()
	
	def _showErrorWindow(self,serverName,serviceName):
		self.alertWindow.show()
		self.playAlertSound()
		notify('NOC : '+serverName,'<b>Service Down !</b><br>You have "'+serviceName+'" service down on `'+serverName+'` server')
	
	def waitForError(self):
		#print "Waiting For Error"
		self.sock.settimeout(None)
		while True:
			data, server = self.sock.recvfrom(255)
			try :
				xRep = json.loads(data)
			except:
				xRep = ''
				
			#print "_____"
			#print xRep
			#print data
			
			if xRep != '':
					if xRep["module"] == 'notify':
						serverTitle = Gtk.servers[xRep["server_id"]]
						if xRep["server_status"] == '1':
							if Gtk.lastServerId != serverTitle + '_1':
								notify('NOC : '+serverTitle,'<b>Service Up</b><br>"'+xRep["service_name"]+'" Service on `'+serverTitle+'` server are up again .')
								Gtk.lastServerId = serverTitle + '_1'
						if xRep["server_status"] == '0':
							if Gtk.lastServerId != serverTitle + '_0':
								GObject.idle_add(self._showErrorWindow,serverTitle,xRep["service_name"])
								Gtk.lastServerId = serverTitle + '_0'
					
			#print data
			#if data == 'SERVER_STATUS_CHANGED:0':
			#	GObject.idle_add(self._showErrorWindow)
			#	#GObject.idle_add(self.playAlertSound)				
			#	
			#if data == 'SERVER_STATUS_CHANGED:1':
			#	notify('Service Up','Some service brought back to life !')
			#	#print "GOT ERROR ALERT ALERT ALERT"
		
	def playAlertSound(self):
		# Create the player_name sink
		Gst.init_check(sys.argv)
		player_name = Gst.ElementFactory.make("playbin2", None)
		path = "file://"+ __file__[:-16] + "../data/media/alert.mp3"
		player_name.set_property("uri", path)
		#player_name.set_property('freq', 1318.5)
		pipeline = Gst.Pipeline(name='note')
		pipeline.add(player_name)
		pipeline.set_state(Gst.State.PLAYING)
	

